2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
10 /*jshint latedef:false */
14 var mw
, StringSet
, log
,
15 hasOwn
= Object
.prototype.hasOwnProperty
,
16 slice
= Array
.prototype.slice
,
17 trackCallbacks
= $.Callbacks( 'memory' ),
22 * FNV132 hash function
24 * This function implements the 32-bit version of FNV-1.
25 * It is equivalent to hash( 'fnv132', ... ) in PHP, except
26 * its output is base 36 rather than hex.
27 * See <https://en.wikipedia.org/wiki/FNV_hash_function>
30 * @param {string} str String to hash
31 * @return {string} hash as an seven-character base 36 string
33 function fnv132( str
) {
34 /*jshint bitwise:false */
35 var hash
= 0x811C9DC5,
38 for ( i
= 0; i
< str
.length
; i
++ ) {
39 hash
+= ( hash
<< 1 ) + ( hash
<< 4 ) + ( hash
<< 7 ) + ( hash
<< 8 ) + ( hash
<< 24 );
40 hash
^= str
.charCodeAt( i
);
43 hash
= ( hash
>>> 0 ).toString( 36 );
44 while ( hash
.length
< 7 ) {
51 StringSet
= window
.Set
|| ( function () {
56 function StringSet() {
59 StringSet
.prototype.add = function ( value
) {
60 this.set[ value
] = true;
62 StringSet
.prototype.has = function ( value
) {
63 return this.set.hasOwnProperty( value
);
69 * Create an object that can be read from or written to from methods that allow
70 * interaction both with single and multiple properties at once.
74 * var collection, query, results;
76 * // Create your address book
77 * collection = new mw.Map();
79 * // This data could be coming from an external source (eg. API/AJAX)
81 * 'John Doe': 'john@example.org',
82 * 'Jane Doe': 'jane@example.org',
83 * 'George van Halen': 'gvanhalen@example.org'
86 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
88 * // You can detect missing keys first
89 * if ( !collection.exists( wanted ) ) {
90 * // One or more are missing (in this case: "Daniel Jackson")
91 * mw.log( 'One or more names were not found in your address book' );
94 * // Or just let it give you what it can. Optionally fill in from a default.
95 * results = collection.get( wanted, 'nobody@example.com' );
96 * mw.log( results['Jane Doe'] ); // "jane@example.org"
97 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
102 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
104 * For backwards-compatibility with mw.config, this can also be `true` in which case values
105 * are copied to the Window object as global variables (T72470). Values are copied in
106 * one direction only. Changes to globals are not reflected in the map.
108 function Map( values
) {
109 if ( values
=== true ) {
112 // Override #set to also set the global variable
113 this.set = function ( selection
, value
) {
116 if ( $.isPlainObject( selection
) ) {
117 for ( s
in selection
) {
118 setGlobalMapValue( this, s
, selection
[ s
] );
122 if ( typeof selection
=== 'string' && arguments
.length
) {
123 setGlobalMapValue( this, selection
, value
);
132 this.values
= values
|| {};
136 * Alias property to the global object.
140 * @param {mw.Map} map
141 * @param {string} key
142 * @param {Mixed} value
144 function setGlobalMapValue( map
, key
, value
) {
145 map
.values
[ key
] = value
;
150 // Deprecation notice for mw.config globals (T58550, T72470)
151 map
=== mw
.config
&& 'Use mw.config instead.'
157 * Get the value of one or more keys.
159 * If called with no arguments, all values are returned.
161 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
162 * @param {Mixed} [fallback=null] Value for keys that don't exist.
163 * @return {Mixed|Object| null} If selection was a string, returns the value,
164 * If selection was an array, returns an object of key/values.
165 * If no selection is passed, the 'values' container is returned. (Beware that,
166 * as is the default in JavaScript, the object is returned by reference.)
168 get: function ( selection
, fallback
) {
170 // If we only do this in the `return` block, it'll fail for the
171 // call to get() from the mutli-selection block.
172 fallback
= arguments
.length
> 1 ? fallback
: null;
174 if ( $.isArray( selection
) ) {
175 selection
= slice
.call( selection
);
177 for ( i
= 0; i
< selection
.length
; i
++ ) {
178 results
[ selection
[ i
] ] = this.get( selection
[ i
], fallback
);
183 if ( typeof selection
=== 'string' ) {
184 if ( !hasOwn
.call( this.values
, selection
) ) {
187 return this.values
[ selection
];
190 if ( selection
=== undefined ) {
194 // Invalid selection key
199 * Set one or more key/value pairs.
201 * @param {string|Object} selection Key to set value for, or object mapping keys to values
202 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
203 * @return {boolean} True on success, false on failure
205 set: function ( selection
, value
) {
208 if ( $.isPlainObject( selection
) ) {
209 for ( s
in selection
) {
210 this.values
[ s
] = selection
[ s
];
214 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
215 this.values
[ selection
] = value
;
222 * Check if one or more keys exist.
224 * @param {Mixed} selection Key or array of keys to check
225 * @return {boolean} True if the key(s) exist
227 exists: function ( selection
) {
230 if ( $.isArray( selection
) ) {
231 for ( s
= 0; s
< selection
.length
; s
++ ) {
232 if ( typeof selection
[ s
] !== 'string' || !hasOwn
.call( this.values
, selection
[ s
] ) ) {
238 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
243 * Object constructor for messages.
245 * Similar to the Message class in MediaWiki PHP.
247 * Format defaults to 'text'.
253 * 'hello': 'Hello world',
254 * 'hello-user': 'Hello, $1!',
255 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
258 * obj = new mw.Message( mw.messages, 'hello' );
259 * mw.log( obj.text() );
262 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
263 * mw.log( obj.text() );
264 * // Hello, John Doe!
266 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
267 * mw.log( obj.text() );
268 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
270 * // Using mw.message shortcut
271 * obj = mw.message( 'hello-user', 'John Doe' );
272 * mw.log( obj.text() );
273 * // Hello, John Doe!
275 * // Using mw.msg shortcut
276 * str = mw.msg( 'hello-user', 'John Doe' );
278 * // Hello, John Doe!
280 * // Different formats
281 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
283 * obj.format = 'text';
284 * str = obj.toString();
289 * // Hello, John "Wiki" <3 Doe!
291 * mw.log( obj.escaped() );
292 * // Hello, John "Wiki" <3 Doe!
297 * @param {mw.Map} map Message store
298 * @param {string} key
299 * @param {Array} [parameters]
301 function Message( map
, key
, parameters
) {
302 this.format
= 'text';
305 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
309 Message
.prototype = {
311 * Get parsed contents of the message.
313 * The default parser does simple $N replacements and nothing else.
314 * This may be overridden to provide a more complex message parser.
315 * The primary override is in the mediawiki.jqueryMsg module.
317 * This function will not be called for nonexistent messages.
319 * @return {string} Parsed message
321 parser: function () {
322 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
326 * Add (does not replace) parameters for `$N` placeholder values.
328 * @param {Array} parameters
331 params: function ( parameters
) {
333 for ( i
= 0; i
< parameters
.length
; i
++ ) {
334 this.parameters
.push( parameters
[ i
] );
340 * Convert message object to its string form based on current format.
342 * @return {string} Message as a string in the current form, or `<key>` if key
345 toString: function () {
348 if ( !this.exists() ) {
349 // Use <key> as text if key does not exist
350 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
351 // format 'escaped' and 'parse' need to have the brackets and key html escaped
352 return mw
.html
.escape( '<' + this.key
+ '>' );
354 return '<' + this.key
+ '>';
357 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
358 text
= this.parser();
361 if ( this.format
=== 'escaped' ) {
362 text
= this.parser();
363 text
= mw
.html
.escape( text
);
370 * Change format to 'parse' and convert message to string
372 * If jqueryMsg is loaded, this parses the message text from wikitext
373 * (where supported) to HTML
375 * Otherwise, it is equivalent to plain.
377 * @return {string} String form of parsed message
380 this.format
= 'parse';
381 return this.toString();
385 * Change format to 'plain' and convert message to string
387 * This substitutes parameters, but otherwise does not change the
390 * @return {string} String form of plain message
393 this.format
= 'plain';
394 return this.toString();
398 * Change format to 'text' and convert message to string
400 * If jqueryMsg is loaded, {{-transformation is done where supported
401 * (such as {{plural:}}, {{gender:}}, {{int:}}).
403 * Otherwise, it is equivalent to plain
405 * @return {string} String form of text message
408 this.format
= 'text';
409 return this.toString();
413 * Change the format to 'escaped' and convert message to string
415 * This is equivalent to using the 'text' format (see #text), then
416 * HTML-escaping the output.
418 * @return {string} String form of html escaped message
420 escaped: function () {
421 this.format
= 'escaped';
422 return this.toString();
426 * Check if a message exists
431 exists: function () {
432 return this.map
.exists( this.key
);
436 log
= ( function () {
437 // Also update the restoration of methods in mediawiki.log.js
438 // when adding or removing methods here.
439 var log = function () {},
440 console
= window
.console
;
448 * Write a message to the console's warning channel.
449 * Actions not supported by the browser console are silently ignored.
451 * @param {...string} msg Messages to output to console
453 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
454 Function
.prototype.bind
.call( console
.warn
, console
) :
458 * Write a message to the console's error channel.
460 * Most browsers provide a stacktrace by default if the argument
461 * is a caught Error object.
464 * @param {Error|...string} msg Messages to output to console
466 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
467 Function
.prototype.bind
.call( console
.error
, console
) :
471 * Create a property in a host object that, when accessed, will produce
472 * a deprecation warning in the console.
474 * @param {Object} obj Host object of deprecated property
475 * @param {string} key Name of property to create in `obj`
476 * @param {Mixed} val The value this property should return when accessed
477 * @param {string} [msg] Optional text to include in the deprecation message
479 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
481 } : function ( obj
, key
, val
, msg
) {
482 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
483 var logged
= new StringSet();
484 function uniqueTrace() {
485 var trace
= new Error().stack
;
486 if ( logged
.has( trace
) ) {
492 Object
.defineProperty( obj
, key
, {
496 if ( uniqueTrace() ) {
497 mw
.track( 'mw.deprecate', key
);
502 set: function ( newVal
) {
503 if ( uniqueTrace() ) {
504 mw
.track( 'mw.deprecate', key
);
522 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
524 * On browsers that implement the Navigation Timing API, this function will produce floating-point
525 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
526 * it will fall back to using `Date`.
528 * @return {number} Current time
531 var perf
= window
.performance
,
532 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
533 return navStart
&& typeof perf
.now
=== 'function' ?
534 function () { return navStart
+ perf
.now(); } :
535 function () { return +new Date(); };
539 * Format a string. Replace $1, $2 ... $N with positional arguments.
541 * Used by Message#parser().
544 * @param {string} formatString Format string
545 * @param {...Mixed} parameters Values for $N replacements
546 * @return {string} Formatted string
548 format: function ( formatString
) {
549 var parameters
= slice
.call( arguments
, 1 );
550 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
551 var index
= parseInt( match
, 10 ) - 1;
552 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
557 * Track an analytic event.
559 * This method provides a generic means for MediaWiki JavaScript code to capture state
560 * information for analysis. Each logged event specifies a string topic name that describes
561 * the kind of event that it is. Topic names consist of dot-separated path components,
562 * arranged from most general to most specific. Each path component should have a clear and
563 * well-defined purpose.
565 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
566 * events that match their subcription, including those that fired before the handler was
569 * @param {string} topic Topic name
570 * @param {Object} [data] Data describing the event, encoded as an object
572 track: function ( topic
, data
) {
573 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
574 trackCallbacks
.fire( trackQueue
);
578 * Register a handler for subset of analytic events, specified by topic.
580 * Handlers will be called once for each tracked event, including any events that fired before the
581 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
582 * the exact time at which the event fired, a string 'topic' property naming the event, and a
583 * 'data' property which is an object of event-specific data. The event topic and event data are
584 * also passed to the callback as the first and second arguments, respectively.
586 * @param {string} topic Handle events whose name starts with this string prefix
587 * @param {Function} callback Handler to call for each matching tracked event
588 * @param {string} callback.topic
589 * @param {Object} [callback.data]
591 trackSubscribe: function ( topic
, callback
) {
593 function handler( trackQueue
) {
595 for ( ; seen
< trackQueue
.length
; seen
++ ) {
596 event
= trackQueue
[ seen
];
597 if ( event
.topic
.indexOf( topic
) === 0 ) {
598 callback
.call( event
, event
.topic
, event
.data
);
603 trackHandlers
.push( [ handler
, callback
] );
605 trackCallbacks
.add( handler
);
609 * Stop handling events for a particular handler
611 * @param {Function} callback
613 trackUnsubscribe: function ( callback
) {
614 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
615 if ( fns
[ 1 ] === callback
) {
616 trackCallbacks
.remove( fns
[ 0 ] );
617 // Ensure the tuple is removed to avoid holding on to closures
624 // Expose Map constructor
627 // Expose Message constructor
631 * Map of configuration values.
633 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
636 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
637 * global `window` object.
639 * @property {mw.Map} config
641 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
645 * Empty object for third-party libraries, for cases where you don't
646 * want to add a new global, or the global is bad and needs containment
654 * Access container for deprecated functionality that can be moved from
655 * from their legacy location and attached to this object (e.g. a global
656 * function that is deprecated and as stop-gap can be exposed through here).
658 * This was reserved for future use but never ended up being used.
660 * @deprecated since 1.22 Let deprecated identifiers keep their original name
661 * and use mw.log#deprecate to create an access container for tracking.
667 * Store for messages.
674 * Store for templates associated with a module.
678 templates
: new Map(),
681 * Get a message object.
683 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
686 * @param {string} key Key of message to get
687 * @param {...Mixed} parameters Values for $N replacements
688 * @return {mw.Message}
690 message: function ( key
) {
691 var parameters
= slice
.call( arguments
, 1 );
692 return new Message( mw
.messages
, key
, parameters
);
696 * Get a message string using the (default) 'text' format.
698 * Shortcut for `mw.message( key, parameters... ).text()`.
701 * @param {string} key Key of message to get
702 * @param {...Mixed} parameters Values for $N replacements
706 return mw
.message
.apply( mw
.message
, arguments
).toString();
710 * No-op dummy placeholder for {@link mw.log} in debug mode.
717 * Client for ResourceLoader server end point.
719 * This client is in charge of maintaining the module registry and state
720 * machine, initiating network (batch) requests for loading modules, as
721 * well as dependency resolution and execution of source code.
723 * For more information, refer to
724 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
729 loader
: ( function () {
732 * Fired via mw.track on various resource loading errors.
734 * @event resourceloader_exception
735 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
736 * object, but in theory module code could manually throw something else, and that
737 * might also end up here.
738 * @param {string} [module] Name of the module which caused the error. Omitted if the
739 * error is not module-related or the module cannot be easily identified due to
741 * @param {string} source Source of the error. Possible values:
743 * - style: stylesheet error (only affects old IE where a special style loading method
745 * - load-callback: exception thrown by user callback
746 * - module-execute: exception thrown by module code
747 * - store-eval: could not evaluate module code cached in localStorage
748 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
749 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
750 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
754 * Fired via mw.track on resource loading error conditions.
756 * @event resourceloader_assert
757 * @param {string} source Source of the error. Possible values:
759 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
760 * bug; see <https://phabricator.wikimedia.org/T59567> for details
764 * Mapping of registered modules.
766 * See #implement and #execute for exact details on support for script, style and messages.
772 * // From mw.loader.register()
773 * 'version': '########' (hash)
774 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
775 * 'group': 'somegroup', (or) null
776 * 'source': 'local', (or) 'anotherwiki'
777 * 'skip': 'return !!window.Example', (or) null
778 * 'module': export Object
780 * // Set from execute() or mw.loader.state()
781 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
783 * // Optionally added at run-time by mw.loader.implement()
785 * 'script': closure, array of urls, or string
786 * 'style': { ... } (see #execute)
787 * 'messages': { 'key': 'value', ... }
794 * The module is known to the system but not yet required.
795 * Meta data is registered via mw.loader#register. Calls to that method are
796 * generated server-side by the startup module.
798 * The module was required through mw.loader (either directly or as dependency of
799 * another module). The client will fetch module contents from the server.
800 * The contents are then stashed in the registry via mw.loader#implement.
802 * The module has been loaded from the server and stashed via mw.loader#implement.
803 * If the module has no more dependencies in-flight, the module will be executed
804 * immediately. Otherwise execution is deferred, controlled via #handlePending.
806 * The module is being executed.
808 * The module has been successfully executed.
810 * The module (or one of its dependencies) produced an error during execution.
812 * The module was registered client-side and requested, but the server denied knowledge
813 * of the module's existence.
819 // Mapping of sources, keyed by source-id, values are strings.
824 // 'sourceId': 'http://example.org/w/load.php'
829 // For queueModuleScript()
830 handlingPendingRequests
= false,
831 pendingRequests
= [],
833 // List of modules to be loaded
837 * List of callback jobs waiting for modules to be ready.
839 * Jobs are created by #enqueue() and run by #handlePending().
841 * Typically when a job is created for a module, the job's dependencies contain
842 * both the required module and all its recursive dependencies.
847 * 'dependencies': [ module names ],
848 * 'ready': Function callback
849 * 'error': Function callback
852 * @property {Object[]} jobs
860 // For addEmbeddedCSS()
862 cssBufferTimer
= null,
863 cssCallbacks
= $.Callbacks(),
864 isIE9
= document
.documentMode
=== 9,
865 rAF
= window
.requestAnimationFrame
|| setTimeout
;
867 function getMarker() {
870 marker
= document
.querySelector( 'meta[name="ResourceLoaderDynamicStyles"]' );
872 mw
.log( 'Create <meta name="ResourceLoaderDynamicStyles"> dynamically' );
873 marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' )[ 0 ];
880 * Create a new style element and add it to the DOM.
883 * @param {string} text CSS text
884 * @param {Node} [nextNode] The element where the style tag
885 * should be inserted before
886 * @return {HTMLElement} Reference to the created style element
888 function newStyleTag( text
, nextNode
) {
889 var s
= document
.createElement( 'style' );
891 s
.appendChild( document
.createTextNode( text
) );
892 if ( nextNode
&& nextNode
.parentNode
) {
893 nextNode
.parentNode
.insertBefore( s
, nextNode
);
895 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
902 * Add a bit of CSS text to the current browser page.
904 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
905 * or create a new one based on whether the given `cssText` is safe for extension.
908 * @param {string} [cssText=cssBuffer] If called without cssText,
909 * the internal buffer will be inserted instead.
910 * @param {Function} [callback]
912 function addEmbeddedCSS( cssText
, callback
) {
915 function fireCallbacks() {
916 var oldCallbacks
= cssCallbacks
;
917 // Reset cssCallbacks variable so it's not polluted by any calls to
918 // addEmbeddedCSS() from one of the callbacks (T105973)
919 cssCallbacks
= $.Callbacks();
920 oldCallbacks
.fire().empty();
924 cssCallbacks
.add( callback
);
927 // Yield once before creating the <style> tag. This lets multiple stylesheets
928 // accumulate into one buffer, allowing us to reduce how often new stylesheets
929 // are inserted in the browser. Appending a stylesheet and waiting for the
930 // browser to repaint is fairly expensive. (T47810)
932 // Don't extend the buffer if the item needs its own stylesheet.
933 // Keywords like `@import` are only valid at the start of a stylesheet (T37562).
934 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
935 // Linebreak for somewhat distinguishable sections
936 cssBuffer
+= '\n' + cssText
;
937 if ( !cssBufferTimer
) {
938 cssBufferTimer
= rAF( function () {
939 // Wrap in anonymous function that takes no arguments
940 // Support: Firefox < 13
941 // Firefox 12 has non-standard behaviour of passing a number
942 // as first argument to a setTimeout callback.
943 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
950 // This is a scheduled flush for the buffer
952 cssBufferTimer
= null;
957 // By default, always create a new <style>. Appending text to a <style> tag is
958 // is a performance anti-pattern as it requires CSS to be reparsed (T47810).
961 // Try to re-use existing <style> tags due to the IE stylesheet limit (T33676).
963 $style
= $( getMarker() ).prev();
964 // Verify that the element before the marker actually is a <style> tag created
965 // by mw.loader (not some other style tag, or e.g. a <meta> tag).
966 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
967 styleEl
= $style
[ 0 ];
968 styleEl
.appendChild( document
.createTextNode( cssText
) );
972 // Else: No existing tag to reuse. Continue below and create the first one.
975 $style
= $( newStyleTag( cssText
, getMarker() ) );
978 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
986 * @param {Array} modules List of module names
987 * @return {string} Hash of concatenated version hashes.
989 function getCombinedVersion( modules
) {
990 var hashes
= $.map( modules
, function ( module
) {
991 return registry
[ module
].version
;
993 return fnv132( hashes
.join( '' ) );
997 * Determine whether all dependencies are in state 'ready', which means we may
998 * execute the module or job now.
1001 * @param {Array} modules Names of modules to be checked
1002 * @return {boolean} True if all modules are in state 'ready', false otherwise
1004 function allReady( modules
) {
1006 for ( i
= 0; i
< modules
.length
; i
++ ) {
1007 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
1015 * Determine whether all dependencies are in state 'ready', which means we may
1016 * execute the module or job now.
1019 * @param {Array} modules Names of modules to be checked
1020 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1022 function anyFailed( modules
) {
1024 for ( i
= 0; i
< modules
.length
; i
++ ) {
1025 state
= mw
.loader
.getState( modules
[ i
] );
1026 if ( state
=== 'error' || state
=== 'missing' ) {
1034 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1035 * pending jobs and modules that depend upon this module. If the given module failed,
1036 * propagate the 'error' state up the dependency tree. Otherwise, go ahead and execute
1037 * all jobs/modules now having their dependencies satisfied.
1039 * Jobs that depend on a failed module, will have their error callback ran (if any).
1042 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1044 function handlePending( module
) {
1045 var j
, job
, hasErrors
, m
, stateChange
;
1047 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1048 // If the current module failed, mark all dependent modules also as failed.
1049 // Iterate until steady-state to propagate the error state upwards in the
1052 stateChange
= false;
1053 for ( m
in registry
) {
1054 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1055 if ( anyFailed( registry
[ m
].dependencies
) ) {
1056 registry
[ m
].state
= 'error';
1061 } while ( stateChange
);
1064 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1065 for ( j
= 0; j
< jobs
.length
; j
++ ) {
1066 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1067 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1068 // All dependencies satisfied, or some have errors
1070 jobs
.splice( j
, 1 );
1074 if ( typeof job
.error
=== 'function' ) {
1075 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1078 if ( typeof job
.ready
=== 'function' ) {
1083 // A user-defined callback raised an exception.
1084 // Swallow it to protect our state machine!
1085 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1090 if ( registry
[ module
].state
=== 'ready' ) {
1091 // The current module became 'ready'. Set it in the module store, and recursively execute all
1092 // dependent modules that are loaded and now have all dependencies satisfied.
1093 mw
.loader
.store
.set( module
, registry
[ module
] );
1094 for ( m
in registry
) {
1095 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1103 * Resolve dependencies and detect circular references.
1106 * @param {string} module Name of the top-level module whose dependencies shall be
1107 * resolved and sorted.
1108 * @param {Array} resolved Returns a topological sort of the given module and its
1109 * dependencies, such that later modules depend on earlier modules. The array
1110 * contains the module names. If the array contains already some module names,
1111 * this function appends its result to the pre-existing array.
1112 * @param {StringSet} [unresolved] Used to track the current dependency
1113 * chain, and to report loops in the dependency graph.
1114 * @throws {Error} If any unregistered module or a dependency loop is encountered
1116 function sortDependencies( module
, resolved
, unresolved
) {
1119 if ( !hasOwn
.call( registry
, module
) ) {
1120 throw new Error( 'Unknown dependency: ' + module
);
1123 if ( registry
[ module
].skip
!== null ) {
1124 /*jshint evil:true */
1125 skip
= new Function( registry
[ module
].skip
);
1126 registry
[ module
].skip
= null;
1128 registry
[ module
].skipped
= true;
1129 registry
[ module
].dependencies
= [];
1130 registry
[ module
].state
= 'ready';
1131 handlePending( module
);
1136 // Resolves dynamic loader function and replaces it with its own results
1137 if ( typeof registry
[ module
].dependencies
=== 'function' ) {
1138 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1139 // Ensures the module's dependencies are always in an array
1140 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1141 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1144 if ( $.inArray( module
, resolved
) !== -1 ) {
1145 // Module already resolved; nothing to do
1148 // Create unresolved if not passed in
1149 if ( !unresolved
) {
1150 unresolved
= new StringSet();
1152 // Tracks down dependencies
1153 deps
= registry
[ module
].dependencies
;
1154 for ( i
= 0; i
< deps
.length
; i
++ ) {
1155 if ( $.inArray( deps
[ i
], resolved
) === -1 ) {
1156 if ( unresolved
.has( deps
[ i
] ) ) {
1157 throw new Error( mw
.format(
1158 'Circular reference detected: $1 -> $2',
1164 unresolved
.add( module
);
1165 sortDependencies( deps
[ i
], resolved
, unresolved
);
1168 resolved
.push( module
);
1172 * Get names of module that a module depends on, in their proper dependency order.
1175 * @param {string[]} modules Array of string module names
1176 * @return {Array} List of dependencies, including 'module'.
1178 function resolve( modules
) {
1180 $.each( modules
, function ( idx
, module
) {
1181 sortDependencies( module
, resolved
);
1187 * Load and execute a script.
1190 * @param {string} src URL to script, will be used as the src attribute in the script tag
1191 * @return {jQuery.Promise}
1193 function addScript( src
) {
1197 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1198 // XHR for a same domain request instead of <script>, which changes the request
1199 // headers (potentially missing a cache hit), and reduces caching in general
1200 // since browsers cache XHR much less (if at all). And XHR means we retrieve
1201 // text, so we'd need to $.globalEval, which then messes up line numbers.
1208 * Queue the loading and execution of a script for a particular module.
1211 * @param {string} src URL of the script
1212 * @param {string} [moduleName] Name of currently executing module
1213 * @return {jQuery.Promise}
1215 function queueModuleScript( src
, moduleName
) {
1216 var r
= $.Deferred();
1218 pendingRequests
.push( function () {
1219 if ( moduleName
&& hasOwn
.call( registry
, moduleName
) ) {
1220 // Emulate runScript() part of execute()
1221 window
.require
= mw
.loader
.require
;
1222 window
.module
= registry
[ moduleName
].module
;
1224 addScript( src
).always( function () {
1225 // 'module.exports' should not persist after the file is executed to
1226 // avoid leakage to unrelated code. 'require' should be kept, however,
1227 // as asynchronous access to 'require' is allowed and expected. (T144879)
1228 delete window
.module
;
1231 // Start the next one (if any)
1232 if ( pendingRequests
[ 0 ] ) {
1233 pendingRequests
.shift()();
1235 handlingPendingRequests
= false;
1239 if ( !handlingPendingRequests
&& pendingRequests
[ 0 ] ) {
1240 handlingPendingRequests
= true;
1241 pendingRequests
.shift()();
1247 * Utility function for execute()
1251 function addLink( media
, url
) {
1252 var el
= document
.createElement( 'link' );
1254 el
.rel
= 'stylesheet';
1255 if ( media
&& media
!== 'all' ) {
1258 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1259 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1262 $( getMarker() ).before( el
);
1266 * Executes a loaded module, making it ready to use
1269 * @param {string} module Module name to execute
1271 function execute( module
) {
1272 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1273 cssHandlesRegistered
= false;
1275 if ( !hasOwn
.call( registry
, module
) ) {
1276 throw new Error( 'Module has not been registered yet: ' + module
);
1278 if ( registry
[ module
].state
!== 'loaded' ) {
1279 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1282 registry
[ module
].state
= 'executing';
1284 runScript = function () {
1285 var script
, markModuleReady
, nestedAddScript
, legacyWait
, implicitDependencies
,
1286 // Expand to include dependencies since we have to exclude both legacy modules
1287 // and their dependencies from the legacyWait (to prevent a circular dependency).
1288 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1290 script
= registry
[ module
].script
;
1291 markModuleReady = function () {
1292 registry
[ module
].state
= 'ready';
1293 handlePending( module
);
1295 nestedAddScript = function ( arr
, callback
, i
) {
1296 // Recursively call queueModuleScript() in its own callback
1297 // for each element of arr.
1298 if ( i
>= arr
.length
) {
1299 // We're at the end of the array
1304 queueModuleScript( arr
[ i
], module
).always( function () {
1305 nestedAddScript( arr
, callback
, i
+ 1 );
1309 implicitDependencies
= ( $.inArray( module
, legacyModules
) !== -1 )
1313 if ( module
=== 'user' ) {
1314 // Implicit dependency on the site module. Not real dependency because
1315 // it should run after 'site' regardless of whether it succeeds or fails.
1316 implicitDependencies
.push( 'site' );
1319 legacyWait
= implicitDependencies
.length
1320 ? mw
.loader
.using( implicitDependencies
)
1321 : $.Deferred().resolve();
1323 legacyWait
.always( function () {
1325 if ( $.isArray( script
) ) {
1326 nestedAddScript( script
, markModuleReady
, 0 );
1327 } else if ( typeof script
=== 'function' ) {
1328 // Pass jQuery twice so that the signature of the closure which wraps
1329 // the script can bind both '$' and 'jQuery'.
1330 script( $, $, mw
.loader
.require
, registry
[ module
].module
);
1333 } else if ( typeof script
=== 'string' ) {
1334 // Site and user modules are legacy scripts that run in the global scope.
1335 // This is transported as a string instead of a function to avoid needing
1336 // to use string manipulation to undo the function wrapper.
1337 $.globalEval( script
);
1341 // Module without script
1345 // Use mw.track instead of mw.log because these errors are common in production mode
1346 // (e.g. undefined variable), and mw.log is only enabled in debug mode.
1347 registry
[ module
].state
= 'error';
1348 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1349 handlePending( module
);
1354 // Add localizations to message system
1355 if ( registry
[ module
].messages
) {
1356 mw
.messages
.set( registry
[ module
].messages
);
1359 // Initialise templates
1360 if ( registry
[ module
].templates
) {
1361 mw
.templates
.set( module
, registry
[ module
].templates
);
1364 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1367 checkCssHandles = function () {
1368 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1369 // one of the cssHandles is fired while we're still creating more handles.
1370 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1372 runScript
= undefined; // Revoke
1375 cssHandle = function () {
1376 var check
= checkCssHandles
;
1378 return function () {
1382 check
= undefined; // Revoke
1388 // Process styles (see also mw.loader.implement)
1389 // * back-compat: { <media>: css }
1390 // * back-compat: { <media>: [url, ..] }
1391 // * { "css": [css, ..] }
1392 // * { "url": { <media>: [url, ..] } }
1393 if ( registry
[ module
].style
) {
1394 for ( key
in registry
[ module
].style
) {
1395 value
= registry
[ module
].style
[ key
];
1398 if ( key
!== 'url' && key
!== 'css' ) {
1399 // Backwards compatibility, key is a media-type
1400 if ( typeof value
=== 'string' ) {
1401 // back-compat: { <media>: css }
1402 // Ignore 'media' because it isn't supported (nor was it used).
1403 // Strings are pre-wrapped in "@media". The media-type was just ""
1404 // (because it had to be set to something).
1405 // This is one of the reasons why this format is no longer used.
1406 addEmbeddedCSS( value
, cssHandle() );
1408 // back-compat: { <media>: [url, ..] }
1414 // Array of css strings in key 'css',
1415 // or back-compat array of urls from media-type
1416 if ( $.isArray( value
) ) {
1417 for ( i
= 0; i
< value
.length
; i
++ ) {
1418 if ( key
=== 'bc-url' ) {
1419 // back-compat: { <media>: [url, ..] }
1420 addLink( media
, value
[ i
] );
1421 } else if ( key
=== 'css' ) {
1422 // { "css": [css, ..] }
1423 addEmbeddedCSS( value
[ i
], cssHandle() );
1426 // Not an array, but a regular object
1427 // Array of urls inside media-type key
1428 } else if ( typeof value
=== 'object' ) {
1429 // { "url": { <media>: [url, ..] } }
1430 for ( media
in value
) {
1431 urls
= value
[ media
];
1432 for ( i
= 0; i
< urls
.length
; i
++ ) {
1433 addLink( media
, urls
[ i
] );
1441 cssHandlesRegistered
= true;
1446 * Add one or more modules to the module load queue.
1451 * @param {string|string[]} dependencies Module name or array of string module names
1452 * @param {Function} [ready] Callback to execute when all dependencies are ready
1453 * @param {Function} [error] Callback to execute when any dependency fails
1455 function enqueue( dependencies
, ready
, error
) {
1456 // Allow calling by single module name
1457 if ( typeof dependencies
=== 'string' ) {
1458 dependencies
= [ dependencies
];
1461 // Add ready and error callbacks if they were given
1462 if ( ready
!== undefined || error
!== undefined ) {
1464 // Narrow down the list to modules that are worth waiting for
1465 dependencies
: $.grep( dependencies
, function ( module
) {
1466 var state
= mw
.loader
.getState( module
);
1467 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1474 $.each( dependencies
, function ( idx
, module
) {
1475 var state
= mw
.loader
.getState( module
);
1476 // Only queue modules that are still in the initial 'registered' state
1477 // (not ones already loading, ready or error).
1478 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1479 // Private modules must be embedded in the page. Don't bother queuing
1480 // these as the server will deny them anyway (T101806).
1481 if ( registry
[ module
].group
=== 'private' ) {
1482 registry
[ module
].state
= 'error';
1483 handlePending( module
);
1486 queue
.push( module
);
1493 function sortQuery( o
) {
1499 if ( hasOwn
.call( o
, key
) ) {
1504 for ( key
= 0; key
< a
.length
; key
++ ) {
1505 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1511 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1512 * to a query string of the form foo.bar,baz|bar.baz,quux
1516 function buildModulesString( moduleMap
) {
1520 for ( prefix
in moduleMap
) {
1521 p
= prefix
=== '' ? '' : prefix
+ '.';
1522 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1524 return arr
.join( '|' );
1528 * Make a network request to load modules from the server.
1531 * @param {Object} moduleMap Module map, see #buildModulesString
1532 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1533 * @param {string} sourceLoadScript URL of load.php
1535 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1536 var query
= $.extend(
1537 { modules
: buildModulesString( moduleMap
) },
1540 query
= sortQuery( query
);
1541 addScript( sourceLoadScript
+ '?' + $.param( query
) );
1545 * Resolve indexed dependencies.
1547 * ResourceLoader uses an optimization to save space which replaces module names in
1548 * dependency lists with the index of that module within the array of module
1549 * registration data if it exists. The benefit is a significant reduction in the data
1550 * size of the startup module. This function changes those dependency lists back to
1551 * arrays of strings.
1554 * @param {Array} modules Modules array
1556 function resolveIndexedDependencies( modules
) {
1558 function resolveIndex( dep
) {
1559 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1561 for ( i
= 0; i
< modules
.length
; i
++ ) {
1562 deps
= modules
[ i
][ 2 ];
1564 for ( j
= 0; j
< deps
.length
; j
++ ) {
1565 deps
[ j
] = resolveIndex( deps
[ j
] );
1572 * Create network requests for a batch of modules.
1574 * This is an internal method for #work(). This must not be called directly
1575 * unless the modules are already registered, and no request is in progress,
1576 * and the module state has already been set to `loading`.
1579 * @param {string[]} batch
1581 function batchRequest( batch
) {
1582 var reqBase
, splits
, maxQueryLength
, b
, bSource
, bGroup
, bSourceGroup
,
1583 source
, group
, i
, modules
, sourceLoadScript
,
1584 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1585 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1587 if ( !batch
.length
) {
1591 // Always order modules alphabetically to help reduce cache
1592 // misses for otherwise identical content.
1595 // Build a list of query parameters common to all requests
1597 skin
: mw
.config
.get( 'skin' ),
1598 lang
: mw
.config
.get( 'wgUserLanguage' ),
1599 debug
: mw
.config
.get( 'debug' )
1601 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1603 // Split module list by source and by group.
1605 for ( b
= 0; b
< batch
.length
; b
++ ) {
1606 bSource
= registry
[ batch
[ b
] ].source
;
1607 bGroup
= registry
[ batch
[ b
] ].group
;
1608 if ( !hasOwn
.call( splits
, bSource
) ) {
1609 splits
[ bSource
] = {};
1611 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1612 splits
[ bSource
][ bGroup
] = [];
1614 bSourceGroup
= splits
[ bSource
][ bGroup
];
1615 bSourceGroup
.push( batch
[ b
] );
1618 for ( source
in splits
) {
1620 sourceLoadScript
= sources
[ source
];
1622 for ( group
in splits
[ source
] ) {
1624 // Cache access to currently selected list of
1625 // modules for this group from this source.
1626 modules
= splits
[ source
][ group
];
1628 currReqBase
= $.extend( {
1629 version
: getCombinedVersion( modules
)
1631 // For user modules append a user name to the query string.
1632 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1633 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1635 currReqBaseLength
= $.param( currReqBase
).length
;
1636 // We may need to split up the request to honor the query string length limit,
1637 // so build it piece by piece.
1638 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1640 moduleMap
= {}; // { prefix: [ suffixes ] }
1642 for ( i
= 0; i
< modules
.length
; i
++ ) {
1643 // Determine how many bytes this module would add to the query string
1644 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1646 // If lastDotIndex is -1, substr() returns an empty string
1647 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1648 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1650 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1651 ? suffix
.length
+ 3 // '%2C'.length == 3
1652 : modules
[ i
].length
+ 3; // '%7C'.length == 3
1654 // If the url would become too long, create a new one,
1655 // but don't create empty requests
1656 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1657 // This url would become too long, create a new one, and start the old one
1658 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1660 l
= currReqBaseLength
+ 9;
1661 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1663 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1664 moduleMap
[ prefix
] = [];
1666 moduleMap
[ prefix
].push( suffix
);
1669 // If there's anything left in moduleMap, request that too
1670 if ( !$.isEmptyObject( moduleMap
) ) {
1671 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1678 * Make a versioned key for a specific module.
1681 * @param {string} module Module name
1682 * @return {string|null} Module key in format '`[name]@[version]`',
1683 * or null if the module does not exist
1685 function getModuleKey( module
) {
1686 return hasOwn
.call( registry
, module
) ?
1687 ( module
+ '@' + registry
[ module
].version
) : null;
1692 * @param {string} key Module name or '`[name]@[version]`'
1695 function splitModuleKey( key
) {
1696 var index
= key
.indexOf( '@' );
1697 if ( index
=== -1 ) {
1698 return { name
: key
};
1701 name
: key
.slice( 0, index
),
1702 version
: key
.slice( index
)
1706 /* Public Members */
1709 * The module registry is exposed as an aid for debugging and inspecting page
1710 * state; it is not a public interface for modifying the registry.
1716 moduleRegistry
: registry
,
1719 * @inheritdoc #newStyleTag
1722 addStyleTag
: newStyleTag
,
1725 * Start loading of all queued module dependencies.
1730 var q
, batch
, concatSource
, origBatch
;
1734 // Appends a list of modules from the queue to the batch
1735 for ( q
= 0; q
< queue
.length
; q
++ ) {
1736 // Only load modules which are registered
1737 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1738 // Prevent duplicate entries
1739 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1740 batch
.push( queue
[ q
] );
1741 // Mark registered modules as loading
1742 registry
[ queue
[ q
] ].state
= 'loading';
1747 // Now that the queue has been processed into a batch, clear the queue.
1748 // This MUST happen before we initiate any eval or network request. Otherwise,
1749 // it is possible for a cached script to instantly trigger the same work queue
1750 // again; all before we've cleared it causing each request to include modules
1751 // which are already loaded.
1754 if ( !batch
.length
) {
1758 mw
.loader
.store
.init();
1759 if ( mw
.loader
.store
.enabled
) {
1762 batch
= $.grep( batch
, function ( module
) {
1763 var source
= mw
.loader
.store
.get( module
);
1765 concatSource
.push( source
);
1771 $.globalEval( concatSource
.join( ';' ) );
1773 // Not good, the cached mw.loader.implement calls failed! This should
1774 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1775 // Depending on how corrupt the string is, it is likely that some
1776 // modules' implement() succeeded while the ones after the error will
1777 // never run and leave their modules in the 'loading' state forever.
1779 // Since this is an error not caused by an individual module but by
1780 // something that infected the implement call itself, don't take any
1781 // risks and clear everything in this cache.
1782 mw
.loader
.store
.clear();
1783 // Re-add the ones still pending back to the batch and let the server
1784 // repopulate these modules to the cache.
1785 // This means that at most one module will be useless (the one that had
1786 // the error) instead of all of them.
1787 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1788 origBatch
= $.grep( origBatch
, function ( module
) {
1789 return registry
[ module
].state
=== 'loading';
1791 batch
= batch
.concat( origBatch
);
1795 batchRequest( batch
);
1799 * Register a source.
1801 * The #work() method will use this information to split up requests by source.
1803 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1805 * @param {string|Object} id Source ID, or object mapping ids to load urls
1806 * @param {string} loadUrl Url to a load.php end point
1807 * @throws {Error} If source id is already registered
1809 addSource: function ( id
, loadUrl
) {
1811 // Allow multiple additions
1812 if ( typeof id
=== 'object' ) {
1813 for ( source
in id
) {
1814 mw
.loader
.addSource( source
, id
[ source
] );
1819 if ( hasOwn
.call( sources
, id
) ) {
1820 throw new Error( 'source already registered: ' + id
);
1823 sources
[ id
] = loadUrl
;
1827 * Register a module, letting the system know about it and its properties.
1829 * The startup modules contain calls to this method.
1831 * When using multiple module registration by passing an array, dependencies that
1832 * are specified as references to modules within the array will be resolved before
1833 * the modules are registered.
1835 * @param {string|Array} module Module name or array of arrays, each containing
1836 * a list of arguments compatible with this method
1837 * @param {string|number} version Module version hash (falls backs to empty string)
1838 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1839 * @param {string|Array|Function} dependencies One string or array of strings of module
1840 * names on which this module depends, or a function that returns that array.
1841 * @param {string} [group=null] Group which the module is in
1842 * @param {string} [source='local'] Name of the source
1843 * @param {string} [skip=null] Script body of the skip function
1845 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1847 // Allow multiple registration
1848 if ( typeof module
=== 'object' ) {
1849 resolveIndexedDependencies( module
);
1850 for ( i
= 0; i
< module
.length
; i
++ ) {
1851 // module is an array of module names
1852 if ( typeof module
[ i
] === 'string' ) {
1853 mw
.loader
.register( module
[ i
] );
1854 // module is an array of arrays
1855 } else if ( typeof module
[ i
] === 'object' ) {
1856 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1861 if ( hasOwn
.call( registry
, module
) ) {
1862 throw new Error( 'module already registered: ' + module
);
1864 if ( typeof dependencies
=== 'string' ) {
1865 // A single module name
1866 deps
= [ dependencies
];
1867 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
1868 // Array of module names or a function that returns an array
1869 deps
= dependencies
;
1871 // List the module as registered
1872 registry
[ module
] = {
1873 // Exposed to execute() for mw.loader.implement() closures.
1874 // Import happens via require().
1878 version
: version
!== undefined ? String( version
) : '',
1879 dependencies
: deps
|| [],
1880 group
: typeof group
=== 'string' ? group
: null,
1881 source
: typeof source
=== 'string' ? source
: 'local',
1882 state
: 'registered',
1883 skip
: typeof skip
=== 'string' ? skip
: null
1888 * Implement a module given the components that make up the module.
1890 * When #load() or #using() requests one or more modules, the server
1891 * response contain calls to this function.
1893 * @param {string} module Name of module and current module version. Formatted
1894 * as '`[name]@[version]`". This version should match the requested version
1895 * (from #batchRequest and #registry). This avoids race conditions (T117587).
1896 * For back-compat with MediaWiki 1.27 and earlier, the version may be omitted.
1897 * @param {Function|Array|string} [script] Function with module code, list of URLs
1898 * to load via `<script src>`, or string of module code for `$.globalEval()`.
1899 * @param {Object} [style] Should follow one of the following patterns:
1901 * { "css": [css, ..] }
1902 * { "url": { <media>: [url, ..] } }
1904 * And for backwards compatibility (needs to be supported forever due to caching):
1907 * { <media>: [url, ..] }
1909 * The reason css strings are not concatenated anymore is bug 31676. We now check
1910 * whether it's safe to extend the stylesheet.
1913 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1914 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1916 implement: function ( module
, script
, style
, messages
, templates
) {
1917 var split
= splitModuleKey( module
),
1919 version
= split
.version
;
1920 // Automatically register module
1921 if ( !hasOwn
.call( registry
, name
) ) {
1922 mw
.loader
.register( name
);
1924 // Check for duplicate implementation
1925 if ( hasOwn
.call( registry
, name
) && registry
[ name
].script
!== undefined ) {
1926 throw new Error( 'module already implemented: ' + name
);
1929 // Without this reset, if there is a version mismatch between the
1930 // requested and received module version, then mw.loader.store would
1931 // cache the response under the requested key. Thus poisoning the cache
1932 // indefinitely with a stale value. (T117587)
1933 registry
[ name
].version
= version
;
1935 // Attach components
1936 registry
[ name
].script
= script
|| null;
1937 registry
[ name
].style
= style
|| null;
1938 registry
[ name
].messages
= messages
|| null;
1939 registry
[ name
].templates
= templates
|| null;
1940 // The module may already have been marked as erroneous
1941 if ( $.inArray( registry
[ name
].state
, [ 'error', 'missing' ] ) === -1 ) {
1942 registry
[ name
].state
= 'loaded';
1943 if ( allReady( registry
[ name
].dependencies
) ) {
1950 * Execute a function as soon as one or more required modules are ready.
1952 * Example of inline dependency on OOjs:
1954 * mw.loader.using( 'oojs', function () {
1955 * OO.compare( [ 1 ], [ 1 ] );
1958 * Since MediaWiki 1.23 this also returns a promise.
1960 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
1962 * @param {string|Array} dependencies Module name or array of modules names the
1963 * callback depends on to be ready before executing
1964 * @param {Function} [ready] Callback to execute when all dependencies are ready
1965 * @param {Function} [error] Callback to execute if one or more dependencies failed
1966 * @return {jQuery.Promise} With a `require` function
1968 using: function ( dependencies
, ready
, error
) {
1969 var deferred
= $.Deferred();
1971 // Allow calling with a single dependency as a string
1972 if ( typeof dependencies
=== 'string' ) {
1973 dependencies
= [ dependencies
];
1977 deferred
.done( ready
);
1980 deferred
.fail( error
);
1983 // Resolve entire dependency map
1984 dependencies
= resolve( dependencies
);
1985 if ( allReady( dependencies
) ) {
1986 // Run ready immediately
1987 deferred
.resolve( mw
.loader
.require
);
1988 } else if ( anyFailed( dependencies
) ) {
1989 // Execute error immediately if any dependencies have errors
1991 new Error( 'One or more dependencies failed to load' ),
1995 // Not all dependencies are ready, add to the load queue
1996 enqueue( dependencies
, function () {
1997 deferred
.resolve( mw
.loader
.require
);
1998 }, deferred
.reject
);
2001 return deferred
.promise();
2005 * Load an external script or one or more modules.
2007 * @param {string|Array} modules Either the name of a module, array of modules,
2008 * or a URL of an external script or style
2009 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
2010 * external script or style; acceptable values are "text/css" and
2011 * "text/javascript"; if no type is provided, text/javascript is assumed.
2013 load: function ( modules
, type
) {
2016 // Allow calling with a url or single dependency as a string
2017 if ( typeof modules
=== 'string' ) {
2018 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
2019 if ( /^(https?:)?\/?\//.test( modules
) ) {
2020 if ( type
=== 'text/css' ) {
2022 // Use properties instead of attributes as IE throws security
2023 // warnings when inserting a <link> tag with a protocol-relative
2024 // URL set though attributes - when on HTTPS. See bug 41331.
2025 l
= document
.createElement( 'link' );
2026 l
.rel
= 'stylesheet';
2028 $( 'head' ).append( l
);
2031 if ( type
=== 'text/javascript' || type
=== undefined ) {
2032 addScript( modules
);
2036 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
2038 // Called with single module
2039 modules
= [ modules
];
2042 // Filter out undefined modules, otherwise resolve() will throw
2043 // an exception for trying to load an undefined module.
2044 // Undefined modules are acceptable here in load(), because load() takes
2045 // an array of unrelated modules, whereas the modules passed to
2046 // using() are related and must all be loaded.
2047 filtered
= $.grep( modules
, function ( module
) {
2048 var state
= mw
.loader
.getState( module
);
2049 return state
!== null && state
!== 'error' && state
!== 'missing';
2052 if ( filtered
.length
=== 0 ) {
2055 // Resolve entire dependency map
2056 filtered
= resolve( filtered
);
2057 // If all modules are ready, or if any modules have errors, nothing to be done.
2058 if ( allReady( filtered
) || anyFailed( filtered
) ) {
2061 // Some modules are not yet ready, add to module load queue.
2062 enqueue( filtered
, undefined, undefined );
2066 * Change the state of one or more modules.
2068 * @param {string|Object} module Module name or object of module name/state pairs
2069 * @param {string} state State name
2071 state: function ( module
, state
) {
2074 if ( typeof module
=== 'object' ) {
2075 for ( m
in module
) {
2076 mw
.loader
.state( m
, module
[ m
] );
2080 if ( !hasOwn
.call( registry
, module
) ) {
2081 mw
.loader
.register( module
);
2083 registry
[ module
].state
= state
;
2084 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1 ) {
2085 // Make sure pending modules depending on this one get executed if their
2086 // dependencies are now fulfilled!
2087 handlePending( module
);
2092 * Get the version of a module.
2094 * @param {string} module Name of module
2095 * @return {string|null} The version, or null if the module (or its version) is not
2098 getVersion: function ( module
) {
2099 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2102 return registry
[ module
].version
;
2106 * Get the state of a module.
2108 * @param {string} module Name of module
2109 * @return {string|null} The state, or null if the module (or its state) is not
2112 getState: function ( module
) {
2113 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2116 return registry
[ module
].state
;
2120 * Get the names of all registered modules.
2124 getModuleNames: function () {
2125 return $.map( registry
, function ( i
, key
) {
2131 * Get the exported value of a module.
2133 * Modules may provide this via their local `module.exports`.
2138 require: function ( moduleName
) {
2139 var state
= mw
.loader
.getState( moduleName
);
2141 // Only ready modules can be required
2142 if ( state
!== 'ready' ) {
2143 // Module may've forgotten to declare a dependency
2144 throw new Error( 'Module "' + moduleName
+ '" is not loaded.' );
2147 return registry
[ moduleName
].module
.exports
;
2151 * @inheritdoc mw.inspect#runReports
2154 inspect: function () {
2155 var args
= slice
.call( arguments
);
2156 mw
.loader
.using( 'mediawiki.inspect', function () {
2157 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2162 * On browsers that implement the localStorage API, the module store serves as a
2163 * smart complement to the browser cache. Unlike the browser cache, the module store
2164 * can slice a concatenated response from ResourceLoader into its constituent
2165 * modules and cache each of them separately, using each module's versioning scheme
2166 * to determine when the cache should be invalidated.
2169 * @class mw.loader.store
2172 // Whether the store is in use on this page.
2175 MODULE_SIZE_MAX
: 100 * 1000,
2177 // The contents of the store, mapping '[name]@[version]' keys
2178 // to module implementations.
2182 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2185 * Construct a JSON-serializable object representing the content of the store.
2187 * @return {Object} Module store contents.
2189 toJSON: function () {
2190 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2194 * Get the localStorage key for the entire module store. The key references
2195 * $wgDBname to prevent clashes between wikis which share a common host.
2197 * @return {string} localStorage item key
2199 getStoreKey: function () {
2200 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2204 * Get a key on which to vary the module cache.
2206 * @return {string} String of concatenated vary conditions.
2208 getVary: function () {
2210 mw
.config
.get( 'skin' ),
2211 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2212 mw
.config
.get( 'wgUserLanguage' )
2217 * Initialize the store.
2219 * Retrieves store from localStorage and (if successfully retrieved) decoding
2220 * the stored JSON value to a plain object.
2222 * The try / catch block is used for JSON & localStorage feature detection.
2223 * See the in-line documentation for Modernizr's localStorage feature detection
2224 * code for a full account of why we need a try / catch:
2225 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2230 if ( mw
.loader
.store
.enabled
!== null ) {
2236 // Disabled because localStorage quotas are tight and (in Firefox's case)
2237 // shared by multiple origins.
2238 // See T66721, and <https://bugzilla.mozilla.org/show_bug.cgi?id=1064466>.
2239 /Firefox|Opera/.test( navigator
.userAgent
) ||
2241 // Disabled by configuration.
2242 !mw
.config
.get( 'wgResourceLoaderStorageEnabled' )
2244 // Clear any previous store to free up space. (T66721)
2245 mw
.loader
.store
.clear();
2246 mw
.loader
.store
.enabled
= false;
2249 if ( mw
.config
.get( 'debug' ) ) {
2250 // Disable module store in debug mode
2251 mw
.loader
.store
.enabled
= false;
2256 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2257 // If we get here, localStorage is available; mark enabled
2258 mw
.loader
.store
.enabled
= true;
2259 data
= JSON
.parse( raw
);
2260 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2261 mw
.loader
.store
.items
= data
.items
;
2265 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2268 if ( raw
=== undefined ) {
2269 // localStorage failed; disable store
2270 mw
.loader
.store
.enabled
= false;
2272 mw
.loader
.store
.update();
2277 * Retrieve a module from the store and update cache hit stats.
2279 * @param {string} module Module name
2280 * @return {string|boolean} Module implementation or false if unavailable
2282 get: function ( module
) {
2285 if ( !mw
.loader
.store
.enabled
) {
2289 key
= getModuleKey( module
);
2290 if ( key
in mw
.loader
.store
.items
) {
2291 mw
.loader
.store
.stats
.hits
++;
2292 return mw
.loader
.store
.items
[ key
];
2294 mw
.loader
.store
.stats
.misses
++;
2299 * Stringify a module and queue it for storage.
2301 * @param {string} module Module name
2302 * @param {Object} descriptor The module's descriptor as set in the registry
2304 set: function ( module
, descriptor
) {
2307 if ( !mw
.loader
.store
.enabled
) {
2311 key
= getModuleKey( module
);
2314 // Already stored a copy of this exact version
2315 key
in mw
.loader
.store
.items
||
2316 // Module failed to load
2317 descriptor
.state
!== 'ready' ||
2318 // Unversioned, private, or site-/user-specific
2319 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2320 // Partial descriptor
2321 // (e.g. skipped module, or style module with state=ready)
2322 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2323 descriptor
.messages
, descriptor
.templates
] ) !== -1
2331 JSON
.stringify( key
),
2332 typeof descriptor
.script
=== 'function' ?
2333 String( descriptor
.script
) :
2334 JSON
.stringify( descriptor
.script
),
2335 JSON
.stringify( descriptor
.style
),
2336 JSON
.stringify( descriptor
.messages
),
2337 JSON
.stringify( descriptor
.templates
)
2339 // Attempted workaround for a possible Opera bug (bug T59567).
2340 // This regex should never match under sane conditions.
2341 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2342 args
[ 1 ] = 'function' + args
[ 1 ];
2343 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2346 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2350 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2351 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2354 mw
.loader
.store
.items
[ key
] = src
;
2355 mw
.loader
.store
.update();
2359 * Iterate through the module store, removing any item that does not correspond
2360 * (in name and version) to an item in the module registry.
2362 prune: function () {
2365 if ( !mw
.loader
.store
.enabled
) {
2369 for ( key
in mw
.loader
.store
.items
) {
2370 module
= key
.slice( 0, key
.indexOf( '@' ) );
2371 if ( getModuleKey( module
) !== key
) {
2372 mw
.loader
.store
.stats
.expired
++;
2373 delete mw
.loader
.store
.items
[ key
];
2374 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2375 // This value predates the enforcement of a size limit on cached modules.
2376 delete mw
.loader
.store
.items
[ key
];
2382 * Clear the entire module store right now.
2384 clear: function () {
2385 mw
.loader
.store
.items
= {};
2387 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2388 } catch ( ignored
) {}
2392 * Sync in-memory store back to localStorage.
2394 * This function debounces updates. When called with a flush already pending,
2395 * the call is coalesced into the pending update. The call to
2396 * localStorage.setItem will be naturally deferred until the page is quiescent.
2398 * Because localStorage is shared by all pages from the same origin, if multiple
2399 * pages are loaded with different module sets, the possibility exists that
2400 * modules saved by one page will be clobbered by another. But the impact would
2401 * be minor and the problem would be corrected by subsequent page views.
2405 update
: ( function () {
2406 var hasPendingWrite
= false;
2408 function flushWrites() {
2410 if ( !hasPendingWrite
|| !mw
.loader
.store
.enabled
) {
2414 mw
.loader
.store
.prune();
2415 key
= mw
.loader
.store
.getStoreKey();
2417 // Replacing the content of the module store might fail if the new
2418 // contents would exceed the browser's localStorage size limit. To
2419 // avoid clogging the browser with stale data, always remove the old
2420 // value before attempting to set the new one.
2421 localStorage
.removeItem( key
);
2422 data
= JSON
.stringify( mw
.loader
.store
);
2423 localStorage
.setItem( key
, data
);
2425 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2428 hasPendingWrite
= false;
2431 return function () {
2432 if ( !hasPendingWrite
) {
2433 hasPendingWrite
= true;
2434 mw
.requestIdleCallback( flushWrites
);
2443 * HTML construction helper functions
2450 * output = Html.element( 'div', {}, new Html.Raw(
2451 * Html.element( 'img', { src: '<' } )
2453 * mw.log( output ); // <div><img src="<"/></div>
2458 html
: ( function () {
2459 function escapeCallback( s
) {
2476 * Escape a string for HTML.
2478 * Converts special characters to HTML entities.
2480 * mw.html.escape( '< > \' & "' );
2481 * // Returns < > ' & "
2483 * @param {string} s The string to escape
2484 * @return {string} HTML
2486 escape: function ( s
) {
2487 return s
.replace( /['"<>&]/g, escapeCallback
);
2491 * Create an HTML element string, with safe escaping.
2493 * @param {string} name The tag name.
2494 * @param {Object} [attrs] An object with members mapping element names to values
2495 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2497 * - string: Text to be escaped.
2498 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2499 * - this.Raw: The raw value is directly included.
2500 * - this.Cdata: The raw value is directly included. An exception is
2501 * thrown if it contains any illegal ETAGO delimiter.
2502 * See <http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2503 * @return {string} HTML
2505 element: function ( name
, attrs
, contents
) {
2506 var v
, attrName
, s
= '<' + name
;
2509 for ( attrName
in attrs
) {
2510 v
= attrs
[ attrName
];
2511 // Convert name=true, to name=name
2515 } else if ( v
=== false ) {
2518 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2521 if ( contents
=== undefined || contents
=== null ) {
2528 switch ( typeof contents
) {
2531 s
+= this.escape( contents
);
2535 // Convert to string
2536 s
+= String( contents
);
2539 if ( contents
instanceof this.Raw
) {
2540 // Raw HTML inclusion
2541 s
+= contents
.value
;
2542 } else if ( contents
instanceof this.Cdata
) {
2544 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2545 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2547 s
+= contents
.value
;
2549 throw new Error( 'mw.html.element: Invalid type of contents' );
2552 s
+= '</' + name
+ '>';
2557 * Wrapper object for raw HTML passed to mw.html.element().
2559 * @class mw.html.Raw
2561 Raw: function ( value
) {
2566 * Wrapper object for CDATA element contents passed to mw.html.element()
2568 * @class mw.html.Cdata
2570 Cdata: function ( value
) {
2576 // Skeleton user object, extended by the 'mediawiki.user' module.
2583 * @property {mw.Map}
2587 * @property {mw.Map}
2592 // OOUI widgets specific to MediaWiki
2596 * Registry and firing of events.
2598 * MediaWiki has various interface components that are extended, enhanced
2599 * or manipulated in some other way by extensions, gadgets and even
2602 * This framework helps streamlining the timing of when these other
2603 * code paths fire their plugins (instead of using document-ready,
2604 * which can and should be limited to firing only once).
2606 * Features like navigating to other wiki pages, previewing an edit
2607 * and editing itself – without a refresh – can then retrigger these
2608 * hooks accordingly to ensure everything still works as expected.
2612 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2613 * mw.hook( 'wikipage.content' ).fire( $content );
2615 * Handlers can be added and fired for arbitrary event names at any time. The same
2616 * event can be fired multiple times. The last run of an event is memorized
2617 * (similar to `$(document).ready` and `$.Deferred().done`).
2618 * This means if an event is fired, and a handler added afterwards, the added
2619 * function will be fired right away with the last given event data.
2621 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2622 * Thus allowing flexible use and optimal maintainability and authority control.
2623 * You can pass around the `add` and/or `fire` method to another piece of code
2624 * without it having to know the event name (or `mw.hook` for that matter).
2626 * var h = mw.hook( 'bar.ready' );
2627 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2629 * Note: Events are documented with an underscore instead of a dot in the event
2630 * name due to jsduck not supporting dots in that position.
2634 hook
: ( function () {
2638 * Create an instance of mw.hook.
2642 * @param {string} name Name of hook.
2645 return function ( name
) {
2646 var list
= hasOwn
.call( lists
, name
) ?
2648 lists
[ name
] = $.Callbacks( 'memory' );
2652 * Register a hook handler
2654 * @param {...Function} handler Function to bind.
2660 * Unregister a hook handler
2662 * @param {...Function} handler Function to unbind.
2665 remove
: list
.remove
,
2670 * @param {...Mixed} data
2674 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2681 // Alias $j to jQuery for backwards compatibility
2682 // @deprecated since 1.23 Use $ or jQuery instead
2683 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2686 * Log a message to window.console, if possible.
2688 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2689 * also in production mode). Gets console references in each invocation instead of caching the
2690 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2693 * @param {string} topic Stream name passed by mw.track
2694 * @param {Object} data Data passed by mw.track
2695 * @param {Error} [data.exception]
2696 * @param {string} data.source Error source
2697 * @param {string} [data.module] Name of module which caused the error
2699 function logError( topic
, data
) {
2702 source
= data
.source
,
2703 module
= data
.module
,
2704 console
= window
.console
;
2706 if ( console
&& console
.log
) {
2707 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2709 msg
+= ' in module ' + module
;
2711 msg
+= ( e
? ':' : '.' );
2714 // If we have an exception object, log it to the error channel to trigger
2715 // proper stacktraces in browsers that support it. No fallback as we have
2716 // no browsers that don't support error(), but do support log().
2717 if ( e
&& console
.error
) {
2718 console
.error( String( e
), e
);
2723 // Subscribe to error streams
2724 mw
.trackSubscribe( 'resourceloader.exception', logError
);
2725 mw
.trackSubscribe( 'resourceloader.assert', logError
);
2728 * Fired when all modules associated with the page have finished loading.
2730 * @event resourceloader_loadEnd
2734 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2735 return mw
.loader
.getState( module
) === 'loading';
2737 // We only need a callback, not any actual module. First try a single using()
2738 // for all loading modules. If one fails, fall back to tracking each module
2739 // separately via $.when(), this is expensive.
2740 loading
= mw
.loader
.using( loading
).then( null, function () {
2741 var all
= $.map( loading
, function ( module
) {
2742 return mw
.loader
.using( module
).then( null, function () {
2743 return $.Deferred().resolve();
2746 return $.when
.apply( $, all
);
2748 loading
.then( function () {
2749 mwPerformance
.mark( 'mwLoadEnd' );
2750 mw
.hook( 'resourceloader.loadEnd' ).fire();
2754 // Attach to window and globally alias
2755 window
.mw
= window
.mediaWiki
= mw
;